package example;

import static org.junit.Assert.fail;

import org.junit.Test;

public class ClassWithThreadingProblemTest {
    boolean failed;

    @Test
    public void twoThreadsShouldFailEventually() throws Exception {
        final ClassWithThreadingProblem classWithThreadingProblem = new ClassWithThreadingProblem();

        Runnable runnable = new Runnable() {
            public void run() {
                int expectedId = classWithThreadingProblem.nextId;
                int actualId = classWithThreadingProblem.takeNextId();
                if (expectedId != actualId)
                    failed = true;
            }
        };

        for (int i = 0; i < 100000; ++i) {
            Thread t1 = new Thread(runnable);
            Thread t2 = new Thread(runnable);
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            if (failed)
                return;
        }

        fail("This test should have exposed a threading issue but it did not.");
    }
}
